package com.ahwei.common.sentinel.aspect;

import com.alibaba.csp.sentinel.Tracer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * <p>
 * AOP实现类，在抛出业务异常时将异常计数值加1
 * </p>
 *
 * @author ahWei
 * @email：ahwei163@qq.com
 * @since 2022-06-06 14:00:20
 */
@Aspect
@Component
public class GlobalRestExceptionAdvice {


    /**
     * 统一异常处理方法的切点
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.ExceptionHandler)")
    public void sentinelResourcePackagePointcut() {
        // Method is empty as this is just a Pointcut, the implementations are
        // in the advices.
    }

    @Around("sentinelResourcePackagePointcut()")
    public Object sentinelResourceAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取请求参数
        Object[] args = joinPoint.getArgs();
        if(args.length <= 0) {
            return null;
        }

        Throwable th = null;
        for(Object o : args) {
            if(o instanceof Throwable) {
                th = (Throwable)o;
                break;
            }
        }
        if(th == null) {
            return null;
        }

        // 2. 对业务异常计数
        Tracer.trace(th);

        // 3. 继续完成请求
        return joinPoint.proceed(args);
    }
}
